#include "sensor_usart.h"
#include "sensor_gpio.h"
#include "rtthread.h"
#include "sensor.h"
#include <string.h>
#include "stdio.h"
#include "netupdata.h"
#include "switch.h"
#include "ota.h"

rt_sem_t sensorSem=NULL;
static rt_timer_t timer1;

/*
now_sensor==2  --�����Ǵ��������ݽ���
*/


struct SensorDataType init_oxygen={13,{0x01,0x10,0x00,0x00,0x00,0x02,0x04,0x00,0x05,0x00,0x1E,0x63,0xA6}};
//struct SensorDataType send_oxygen={8,{0x01,0x03,0x00,0x10,0x00,0x08,0x45,0xC9}};
struct SensorDataType send_oxygen={8,{0x01,0x03,0x00,0x00,0x00,0x34,0x44,0x1D}};
//struct SensorDataType ackHead_oxygen={3,{0x01,0x03,0x10}};
struct SensorDataType ackHead_oxygen={3,{0x01,0x03,0x68}};
//uint32_t ackLen_oxygen=21;
uint32_t ackLen_oxygen=109;

float sensor_data[40]={0};//��һ��Ԫ�ر�ʾ�������м���������ӵڶ���Ԫ�ر�ʾ����������ֵ
uint8_t initflag=0;

uart_484_get_data 		p_getdata;
uart_485_rx_get_frame   p_get_frame;
uart_485_rx_restart     p_rx_restart;
uart_485_hex_send       p_hex_send;

rt_thread_t sensorThread=NULL;     //存储OTA线程号用于终止和启动

void sensorModeThreadStop()
{
    if(sensorThread!=NULL)rt_thread_delete(sensorThread);
    rt_kprintf("Sensor thread stop!!!\n");
}




void sensorThreadEntry(void *para)
{
    while (1)
    {
        rt_sem_take(sensorSem, RT_WAITING_FOREVER);
        if (otaStatusGet() == 1)
        {
            continue;
        }
        get_sensor_data(2,2);

        swTimeUp();


    }
}

void sensor_init(){
    //HAL_SENSOR_MspInit();    在HAL_Init()函数中修改代码进行工程配置
    MX_SENSOR_GPIO_Init();
    MX_USART3_UART_Init();
    MX_UART4_Init();
}

void sensor_init_send(uint32_t sensor_id)
{
    rt_kprintf("Init sensor %d!!!\r\n",sensor_id);
    switch(sensor_id){
    case 2:
        (*p_hex_send)(init_oxygen);
        rt_thread_mdelay(60*1000);
        break;
    default:
        rt_kprintf("Can't find sensor %d init!!!\r\n",sensor_id);
        break;
    }
}
void get_sensor_data(uint8_t idFor485,uint32_t sensor_id)
{
    uint32_t tryNum=5;
    uint8_t* data;
    switch(idFor485){
    case 1:
        p_getdata=uart_484_1_get_data;
        p_get_frame=uart_485_1_rx_get_frame;
        p_rx_restart=uart_485_1_rx_restart;
        p_hex_send=uart_485_1_hex_send;
        break;
    case 2:
        p_getdata=uart_484_2_get_data;
        p_get_frame=uart_485_2_rx_get_frame;
        p_rx_restart=uart_485_2_rx_restart;
        p_hex_send=uart_485_2_hex_send;
        break;
    default:
        rt_kprintf("Can't find 485 %d !!!\r\n",idFor485);
        return;
    }
    if(initflag!=1){
        sensor_init_send(sensor_id);  //必须给p_hex_send赋值才能调用
        initflag=1;
    }
    switch(sensor_id){
    case 2:
        for(int i=0;i<tryNum;i++){
            if((*p_getdata)(send_oxygen,ackHead_oxygen,ackLen_oxygen,10000)==0){
                data=(*p_get_frame)();
                sensor_data[0]=3;
/*                sensor_data[1]=(data[5]*256+data[6])/100.0;
                sensor_data[2]=(data[7]*256+data[8])/100.0;
                sensor_data[3]=(data[11]*256+data[12])/100.0;
                */
                sensor_data[1]=(data[37]*256+data[38])/100.0;
                sensor_data[2]=(data[43]*256+data[44])/100.0;
                sensor_data[3]=(data[80]*256+data[81])/1000.0;
//                char temp[100];
//                rt_memset(temp, 0, 100);
//                sprintf(temp,"Oxygen sensor data:%f,%f,%f!!!\r\n",sensor_data[1],sensor_data[2],sensor_data[3]);
//                rt_kprintf("%s",temp);
                rt_kprintf("Temperature: %d \n", (int)sensor_data[1]);
                rt_kprintf("oxygen_ratio: %d % \n", (int)sensor_data[2]);
                rt_kprintf("oxygen_value: %d mgL\n", (int)sensor_data[3]);
//                rt_kprintf("Temperature: %d \n", (int)sensor_data[1]);
//                rt_kprintf("oxygen_value: %d mgL \n", (int)sensor_data[2]);
//                rt_kprintf("PH_value: %d \n", (int)sensor_data[3]);
                struct UpSensorData updata={
                        .BizType=4,
                        .temperature=sensor_data[1],
                        .oxygen_ratio=sensor_data[2],
                        .oxygen_value=sensor_data[3]
                };
                updata_SensorStruct_Set(&updata);//设置数据同时通知上报


				//向云平台上报
                break;
            }
            (*p_rx_restart)();
            if(i==tryNum-1){
                sensor_init_send(sensor_id);
                rt_kprintf("Can't find sensor data!!!\r\n");
            }
        }
        break;
    default:
        rt_kprintf("Can't find sensor %d!!!\r\n",sensor_id);
        return;
    }
}

uint8_t uart_484_1_send_cmd(char *cmd, char *ack, uint32_t timeout)
{
    uint8_t *ret = NULL;
    if (cmd != NULL)
    {
        uart_485_1_rx_restart();
        uart_485_1_printf("%s\r\n", cmd);
    }

    if ((ack == NULL) || (timeout == 0))
    {
        return 0;
    }
    else
    {
        while (timeout > 0)
        {
            ret = uart_485_1_rx_get_frame();
            if (ret != NULL)
            {
                if (strstr((const char *)ret, ack) != NULL)
                {
                    return 0;
                }
                else
                {
                    uart_485_1_rx_restart();
                }
            }
            timeout--;
            rt_thread_mdelay(1);
        }

        return 1;
    }
}

uint8_t uart_484_1_get_data(struct SensorDataType cmd,struct SensorDataType ackHead,uint32_t acklen,uint32_t timeout)
{
    uint8_t *ret = NULL;
    uint32_t i;

    if (cmd.len != 0)
    {
        uart_485_1_rx_restart();
        uart_485_1_hex_send(cmd);  //����ʮ������
    }

    if ((ackHead.len == 0) || (timeout == 0))
    {
        return 0;
    }
    else
    {
        while (timeout > 0)
        {
            ret = uart_485_1_rx_get_frame();
            if (ret != NULL)
            {
                if (uart_485_1_rx_get_frame_len()==acklen)
                {		
                    //rt_kprintf("\r\n&&%d&&\r\n",uart_485_1_rx_get_frame_len());   //debug��־
                    for(i=0;i<ackHead.len;i++){
                        //rt_kprintf("\r\n&&%d&&%d&&%d&&\r\n",i,ret[i],ackHead.data[i]);   //debug��־
                        if(ret[i]!=ackHead.data[i])break;
                    }
                    if(i==ackHead.len)
                    {return 0;}
                    else
                        uart_485_1_rx_restart();
                }
                else
                {
                    uart_485_1_rx_restart();
                }
            }
            timeout--;
            rt_thread_mdelay(1);
        }
        return 1;
    }
}

uint8_t uart_484_2_get_data(struct SensorDataType cmd,struct SensorDataType ackHead,uint32_t acklen,uint32_t timeout)
{
    uint8_t *ret = NULL;
    uint32_t i;

    if (cmd.len != 0)
    {
        uart_485_2_rx_restart();
        uart_485_2_hex_send(cmd);  // 发送十六进制命令
    }

    if ((ackHead.len == 0) || (timeout == 0))
    {
        return 0;
    }
    else
    {
        while (timeout > 0)
        {
            ret = uart_485_2_rx_get_frame();
            if (ret != NULL)
            {
                uint16_t len = uart_485_2_rx_get_frame_len();
                rt_kprintf("Received data length: %d\n", len);
                if (len == acklen)
                {
                    rt_kprintf("Received data header: ");
                    for(i=0;i<ackHead.len;i++){
                        rt_kprintf("%02X ", ret[i]);
                        if(ret[i]!=ackHead.data[i])break;
                    }
                    rt_kprintf("\n");
                    if(i==ackHead.len)
                    {return 0;}
                    else
                        uart_485_2_rx_restart();
                }
                else
                {
                    uart_485_2_rx_restart();
                }
            }
            timeout--;
            rt_thread_mdelay(1);
        }
        return 1;
    }
}

/* 定时器 1 超时函数 */
static void timeout1(void *parameter)
{
    rt_sem_release(sensorSem);}

int sensorModuleInit()
{
    sensor_init();
    sensorSem = rt_sem_create("sensSem", 0, RT_IPC_FLAG_FIFO);
    timer1 = rt_timer_create("timer1", timeout1,RT_NULL, 5*1000,RT_TIMER_FLAG_PERIODIC);
    sensorThread=rt_thread_create("sensor", sensorThreadEntry, NULL, 4096, 21, 5);  //名字，入口，参数，堆大小,优先级，时间片(数目)
    if(sensorSem==NULL || sensorThread==NULL||NULL==timer1)
       {
           rt_kprintf("[sensor] init fail\n");
           return 1;
       }

    rt_thread_startup(sensorThread);
    rt_timer_start(timer1);
    rt_kprintf("Sensor thread startup!!!!\n");
    return 0;
}

INIT_APP_EXPORT(sensorModuleInit);

